<?php

namespace frontend\controllers;

use Yii;
use yii\helpers\Url;
use common\models\Page;
use common\models\Note;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * PageController implements the CRUD actions for Page model.
 */
class PageController extends Controller {

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Page models.
     * @return mixed
     */
    public function actionIndex() {
        //  无列表页，跳转到网站首页
        return $this->redirect(Url::toRoute('/site/index', TRUE));
    }

    /**
     * Displays a single Page model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($slug) {
        //  当前页面的获取访问量数组
        $model = Page::find()->where(['slug' => $slug])->andWhere(['enabled' => 1])->asArray()->one();
        if (!empty($model)) {
            $hot = Note::find()->with('c')->asArray()->orderBy('view desc')->limit(10)->all();
            $tag = Note::find()->groupBy(['tag'])->orderBy('view desc')->asArray()->all();
            return $this->render('view', [
                        'model' => $model,
                        'hot' => $hot,
                        'tag' => $tag,
            ]);
        } else {
            throw new NotFoundHttpException(Yii::t('common', 'NotFound'));
        }
    }

    /**
     * Finds the Page model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Page the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id) {
        if (($model = Page::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException(Yii::t('common', 'NotFound'));
        }
    }

}
